﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Coldairarrow.Util.Helper;
using Coldairarrow.Business.AOP;
using System.Linq.Expressions;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ProjectStatuLogBusiness : BaseBusiness<PB_ProjectStatuLog>, IPB_ProjectStatuLogBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_ProjectStatuLogBusiness(IDbAccessor db,IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_ProjectStatuLog>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_ProjectStatuLog>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ProjectStatuLog, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_ProjectStatuLog> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_ProjectStatuLog data)
        {
            string sql = "select * from PB_ProjectStatuLog WHERE  BuildingnumberId='"+data.BuildingnumberId+"' AND  to_days(CreateTime) = to_days(now())";
            var list = await Db.GetListBySqlAsync<PB_ProjectStatuLog>(sql) ;
            if (list.Count>0) {
                throw new BusException("本日已提交进度");
            }
            data.CreateTime = DateTime.Now;
            data.CreatorId = _operator.UserId;
            if (data.Status == "3")
            {
                string sqlMain = @"update PB_Buildingnumber set IsInspection=0 where Id='" + data.BuildingnumberId + "'";
                await ExecuteSqlAsync(sqlMain);
            }
            await InsertAsync(data);
          
           
        }
        public async Task<List<Base_EnumItem>> GetEnumItem()
        {
            var q = Db.GetIQueryable<Base_EnumItem>().Where(x => x.EnumCode == "ProjectStatu");
            return await q.ToListAsync();
        }


        public async Task UpdateDataAsync(PB_ProjectStatuLog data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        /// <summary>
        ///项目现场状态提示消息当天没有记录推送钉钉消息
        /// </summary>
        /// <returns></returns>
        /// 

        public async Task<PB_ProjectStatuLogMessage> GetProjectMessAge()
        {
            PB_ProjectStatuLogMessage pB_ProjectStatuLogMessage = new PB_ProjectStatuLogMessage();
            //获取所有技术负责人信息
            string SQL = "select U.* from PB_Buildingnumber AS P INNER JOIN Base_User AS  U on P.TechnicalDirector = U.Id WHERE P.TechnicalDirector is not null  GROUP BY  P.TechnicalDirector";
            List<Base_User> Base_Users = Db.GetListBySql<Base_User>(SQL);//获取已经有项目负责人的信息
            List<PB_Buildingnumber> pB_Projects = new List<PB_Buildingnumber>();//获取项目总条数
            foreach (var baseuse in Base_Users) {
                String ProjectList = "select * from PB_Buildingnumber WHERE TechnicalDirector = '" + baseuse .Id+ "'";
                List<PB_Buildingnumber> Project = Db.GetListBySql<PB_Buildingnumber>(ProjectList);
                foreach(var ITEM in Project)
                {
                    pB_Projects.Add(ITEM);
                }
            }
            //拿到所有的楼号
            List<PB_Buildingnumber> pB_Buildingnumbers = new List<PB_Buildingnumber>();
            foreach (var xiangmulist in pB_Projects) {
                string BuildingnumberList = "select * from PB_Buildingnumber WHERE Id ='"+xiangmulist.Id+"'";
                List<PB_Buildingnumber> Buildingnumber = Db.GetListBySql<PB_Buildingnumber>(BuildingnumberList);
                foreach (var bunumber in Buildingnumber) {
                    pB_Buildingnumbers.Add(bunumber);
                }
            }
          
            //获取要推送的现场进度数据
            List<StatuLogMessageList> messageLists = new List<StatuLogMessageList>(); 
            foreach (var message in pB_Buildingnumbers) { 
            string  massagesql= "select* from PB_ProjectStatuLog where ProjectId = '"+message.ProjectId+"' AND BuildingnumberId = '"+message.Id+ "' and to_days(CreateTime) = to_days(now())";
                List<PB_ProjectStatuLog> Buildingnumber = Db.GetListBySql<PB_ProjectStatuLog>(massagesql);
                if (Buildingnumber.Count==0) {
                    Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
                    PB_Project pB_Project =await Db.GetIQueryable<PB_Project>().Where(m=>m.Id==message.ProjectId).FirstOrDefaultAsync();
                    Base_User User = await Db.GetIQueryable<Base_User>().Where(m => m.Id == message.TechnicalDirector).FirstOrDefaultAsync();
                    StatuLogMessageList statuLogMessageList = new StatuLogMessageList();
                    statuLogMessageList.Phone = User.Telephone;
                    statuLogMessageList.Name = User.RealName;
                    statuLogMessageList.PeojectId = message.ProjectId;
                    statuLogMessageList.ProjectName = pB_Project.Name;
                    statuLogMessageList.BuildingnumberId = message.Id;
                    statuLogMessageList.Buildingnumber = message.Buildingnumber;
                    statuLogMessageList.Message =DateTime.Now.ToString("g")+ pB_Project.Name+"(" + message.Buildingnumber + ")待更新进度";             
                    //判断用户钉钉号不为空 为空不推送钉钉消息
                    if (User.DingUserId!=null) {
                        List<string> vs = new List<string>();
                        vs.Add(User.DingUserId);
                        input.ExecutorIds = vs;
                        input.Str = DateTime.Now.ToString("g")+statuLogMessageList.Message;
                        input.BillId = message.ProjectId;
                        //推送钉钉记录
                        DingHelper.sendMessage(input);
                        string strSQL = @"SELECT * FROM `Base_OverFlowTask`    WHERE BillId='"+message.Id+"'";
                        var res = await Db.GetListBySqlAsync<PB_DeliveryPlanDetails2DTO>(strSQL);
                        if (res.Count==0) {
                            await Db.ExecuteSqlAsync("INSERT INTO Base_OverFlowTask VALUES ('" + message.Id + "','ProjectStatus',0)");
                        }
                        
                    }
                    messageLists.Add(statuLogMessageList);
                }
            }
            pB_ProjectStatuLogMessage.MessAgeList = messageLists;
            return  pB_ProjectStatuLogMessage;
        }

        /// <summary>
        /// pc端获取项目进度数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public  async Task<PageResult<PB_ProjectStatuLoDto>> GetPB_ProjectStatuLoDtoListAsync(PageInput<PB_ProjectStatuLogConditionDTO> input)
        {
            string sql = @"SELECT
	* 
FROM
	(
	SELECT
	b.Id Bulid,
b.Buildingnumber AS BulidNo,
c.`Name` AS ProjectName,
u.RealName TechnicalDirector,
e.`Name` Typename,
b.StartingLayer AS Qishi,
b.TerminationLayer AS Zhongzhi,
b.StandsNumber AS StandsNumber,
b.LiftPlatNums AS LiftPlatNums,
		a.ProjectId,
		a.BuildingnumberId,
		a.CreateTime,
		a.Remarks,
		a.`Status`,
		a.NumberLayers  ThisBuilNo,
		ROW_NUMBER() over ( PARTITION BY a.ProjectId, a.BuildingnumberId ORDER BY a.CreateTime DESC ) AS rowsid 
	FROM
		PB_ProjectStatuLog  as a
		LEFT JOIN PB_Buildingnumber as b ON  a.BuildingnumberId=b.Id
		LEFT JOIN PB_Project as c ON a.ProjectId =c.Id
LEFT JOIN Base_User as u ON b.TechnicalDirector=u.Id
LEFT JOIN Base_EnumItem as e on c.Businesstype=e.`Value`
	) AS t 
WHERE
	rowsid =1  {0}
	";
            //检索条件
            string _where = "";
            if (!input.Search.Keyword.IsNullOrEmpty()) {
                _where = " and (t.ProjectName  like '%"+input.Search.Keyword.Trim()+ "%' OR t.BulidNo like '%" + input.Search.Keyword.Trim() + "%' OR t.Remarks like '%" + input.Search.Keyword.Trim() + "%')";
            }
            if (!input.Search.Status.IsNullOrEmpty()) {
                _where += " and t.Status='"+input.Search.Status+"'";
            }
            if (!input.Search.StartDate.IsNullOrEmpty()) {
                _where += " and t.CreateTime>='"+ Convert.ToDateTime(input.Search.StartDate).ToString("yyyy-MM-dd 00:00:00") + "'";
            }
            if (!input.Search.EndDate.IsNullOrEmpty()) {
                _where += " and t.CreateTime<='"+  Convert.ToDateTime(input.Search.EndDate).ToString("yyyy-MM-dd 23:59:59") + "'";
            }
            if (!input.SortField.IsNullOrEmpty())
            {
                _where += " ORDER BY " + input.SortField;
            }
            if (!input.SortType.IsNullOrEmpty())
            {
                _where += " " + input.SortType;
            }

            sql = string.Format(sql,_where );
            var res = await Db.GetListBySqlAsync<PB_ProjectStatuLoDto>(sql);
            int pagecount;//总页数
            List<PB_ProjectStatuLoDto> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<PB_ProjectStatuLoDto> productes = new List<PB_ProjectStatuLoDto>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<PB_ProjectStatuLoDto> { Data = productes, Total = pagees };
        }
    }
        #endregion

        #region 私有成员

        #endregion
    }
